<template>
  <el-select
    :loading="loading"
    :filterable="true"
    v-bind="props.props"
    v-model="modelValue"
    @visible-change="handleVisibleChange"
    @change="value => emit('change', { value, label: options.find(option => option.value === value)?.label })"
  >
    <template v-if="!!options.length">
      <el-option v-for="option in options" :value="option.value" :label="option.label" />
    </template>
    <template v-else-if="typeof modelValue !== 'undefined' && !!modelDefault">
      <el-option :value="modelValue" :label="modelDefault" />
    </template>
    <template v-for="slot in Object.keys($slots).filter(slot => slot !== 'default')" #[slot]="scope">
      <slot :name="slot" v-bind="scope" />
    </template>
  </el-select>
</template>

<script setup lang="ts">
import type { MerakXFormItemSelect, MerakXFormItemOptions } from "../index";

import { ref, computed } from "vue";

import { ElSelect, ElOption } from "element-plus";

const props = defineProps<MerakXFormItemSelect & MerakXFormItemOptions>();

const modelValue = defineModel<any>("value");
const modelDefault = defineModel<string>("default");
const modelIngoreQuery = defineModel<boolean>("ingoreQuery", { default: false });

const emit = defineEmits<{
  change: [arg: any];
}>();

const loading = ref(false);

const options = computed(() => [...(props.options ?? [])]);

const handleVisibleChange = async (visible: boolean) => {
  if (!!visible && (options.value.length === 0 || !modelIngoreQuery.value)) {
    modelIngoreQuery.value = true;
    loading.value = true;
    await props.queryOptions?.(props.field);
    loading.value = false;
  }
};
</script>
